<?php

namespace app\common\command;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\Children;
use app\admin\model\market\Acceleration;
use app\admin\model\shopro\goods\Goods;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\user\WalletLog;
use app\common\model\shopro\DividendLog;
use app\common\model\shopro\ReleaseLog;
use app\common\model\User;
use app\common\model\UserStaticLogModel;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\exception\HttpResponseException;

class Rebatemoney extends Command
{
    protected function configure()
    {
        $this->setName('rebatemoney')->setHelp('返利金')->setDescription('返利金');
    }
    protected function execute(Input $input, Output $output)
    {
        $is_release = config('site.is_release');
        if ($is_release == 1) {
            ini_set('memory_limit', "-1");
        }
//        $data = db('user_principal_log')->whereTime('createtime', 'd')->where(['memo'=>'静态收益'])->delete();
//        $data = db('user_golden_log')->whereTime('createtime', 'd')->where(['memo'=>'静态收益'])->delete();
//        foreach ($data as $k=>$v){
//             $r= db('user')->where(['id'=>$v['user_id']])->update(['golden'=>$v['before']]);
//             dump($r);
//        }
//        $data = db('shopro_user_wallet_log')->whereTime('createtime', 'd')->where(['memo'=>'静态收益'])->delete();
//        dump(count($data));
//        exit();
//        var_dump($partner_day   = config('site.settlement_day'));
//        $end_time      = strtotime(date('Y-m-d 23:59:59'));
//        $sta_time      = strtotime('-'.$partner_day.' days', strtotime(date('Y-m-d')));
//        dump($end_time);
//        dump($sta_time);
//        exit();

        $next_rebate_time =  db('config')->where(['name'=>'end_time'])->value('value');
        if(time() < $next_rebate_time){
            echo '未到分成时间';
            return;
        }
        $xia_time = 86400 * config('site.settlement_day') + strtotime('today');
        db('config')->where(['name'=>'end_time'])->update(['value'=>$xia_time,'content'=>date('Y-m-d H:i:s',$xia_time)]);
        $dividendLogModel = new DividendLog();
        $userModel        = new User();
        $model            = new UserStaticLogModel();
        $user_idArr       = $userModel->where('principal', '>', 0)->column('id');
        $data             = $model->with(['user'])->where('status', '=', 1)->whereIn('user_id',
            $user_idArr)->where('rebate_time', '<', time())->where('order_id','>',0)->select();

        $info = $dividendLogModel->where(['dividend_type' => 4])->whereTime('createtime', 'd')->find();
//        $data = $model->whereIn('user_id', $user_idArr)->where('status','=',1)->select();
        if ($data) {
            $orderModel    = new Order();
            $partner_day   = config('site.settlement_day');
            $partner_scale = config('site.turnover_scale') / 100;
            $end_time      = strtotime(date('Y-m-d 23:59:59'));
            $sta_time      = strtotime('-'.$partner_day.' days', strtotime(date('Y-m-d')));
            $order_amount  = $orderModel->where('is_yye','=',0)->whereNull('activity_type')->whereIn('status',
                    'paid,completed')->whereBetween('createtime', [$sta_time, $end_time])->sum('order_amount') ?? 0;
            $num           = count($data);
            $fen_money     = bcmul($order_amount, $partner_scale, 2);
            $personage     = $fen_money / $num;
            $golen_scale   = config('site.golen_scale') / 100;        //金豆比例
            $slive_scale   = (100 - config('site.golen_scale')) / 100;//银豆比例
            $user_ids      = '';
            $all_golden    = 0;
            $all_slive     = 0;
            $all_score     = 0;
            if ($personage) {
                Db::startTrans();
                try {
                    foreach ($data as $k => $v) {
                        $user = $userModel->where('id', '=', $v['user_id'])->where('principal', '>', 0)->find();
                        if ($user) {
                            if ($user->principal < $personage) {
                                $personage = $user->principal;
                                $v->status = 2;
                                $v->save();
                            }
                            $all_score += $personage;
                            $user_ids  .= ','.$v->user_id;
                            WalletService::change($v->user_id, 'principal', -$personage, 'jingtai_release',
                                ['user_static_id' => $v->id],
                                '静态收益');
                            //金币
                            $goods_golen_scale =  Goods::where(['id'=>$v['goods_id']])->value('golen_scale');
                            if($goods_golen_scale){
                                $golen_scale   = $goods_golen_scale / 100;        //金豆比例
                                $slive_scale   = (100 - $goods_golen_scale) / 100;//银豆比例
                            }
                            $golden = bcmul($personage, $golen_scale, 2);
                            if ($golden > 0) {
                                WalletService::change($v->user_id, 'golden', $golden, 'jingtai_golden', [], '静态收益');
                                $all_golden += $golden;
                            }
                            //银币
                            $slive = bcmul($personage, $slive_scale, 2);
                            if ($slive > 0) {
                                WalletService::change($v->user_id, 'silver', $slive, 'jingtai_slive', [], '静态收益');
                                $all_slive += $slive;
                            }
                        } else {
                            $v->status = 2;
                            $v->save();
                        }
                    }
                    $dividendLogModel->create([
                        'user_ids'       => $user_ids,
                        'user_num'       => $num,
                        'actual_receipt' => $fen_money,//总数
                        'all_score'      => $all_score,//已分
                        'remaining'      => $fen_money - $all_score,//总数
                        'all_golden'     => $all_golden,
                        'all_slive'      => $all_slive,
                        'dividend_type'  => 4
                    ]);
                    Db::commit();
                    echo '操作成功';
                } catch (HttpResponseException $e) {
                    Db::rollback();
                    $data    = $e->getResponse()->getData();
                    $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
                    format_log_error($e, 'Rebatemoney.HttpResponseException', $message);
                }
            }
        }
    }

}
